package com.lianzhihui.romeex;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.hyphenate.chat.ChatClient;
import com.hyphenate.helpdesk.easeui.UIProvider;
import com.lianzhihui.romeex.bean.WalletMainBean;
import com.lianzhihui.romeex.config.AppConstants;
import com.lianzhihui.romeex.database.DataBaseConfig;
import com.lianzhihui.romeex.net.HttpManager;
import com.lianzhihui.romeex.ui.MainActivity;
import com.lianzhihui.romeex.utils.LanguageUtil;
import com.lianzhihui.romeex.utils.LogUtil;
import com.lianzhihui.romeex.utils.PreferenceUtils;
import com.lianzhihui.romeex.utils.UserUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.commonsdk.UMConfigure;
import com.zhouyou.http.EasyHttp;

import java.util.Locale;

import cn.jpush.android.api.JPushInterface;

/**
 * Copyright (C), 2019-2020
 * FileName: MyApplication
 * Author: ZhaoFeng
 * <p>
 * Date: 2020/10/21 16:28
 * Description:
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
public class MyApplication extends Application {

    public static Context mContext;
    public static boolean debug = false;
    //    public static boolean debug = true;
    public static int environment;

    public static int getEnvironment() {
        return environment;
    }

    public static void setEnvironment(int environment) {
        MyApplication.environment = environment;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;

        String pkName = this.getPackageName();
        try {
            String versionName = this.getPackageManager().getPackageInfo(
                    pkName, 0).versionName;
            if (versionName.contains("test")) {
                Log.e("ramon", "测试服务器");
                setEnvironment(AppConstants.AppStatus.TEST);
            } else {
                Log.e("ramon", "正式服务器");
                setEnvironment(AppConstants.AppStatus.RELEASE);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("ramon", e.toString());
        }

//        setEnvironment(AppConstants.AppStatus.TEST);
//        setEnvironment(AppConstants.AppStatus.RELEASE);
        //初始化网络配置
        EasyHttp.init(this);
        HttpManager.initBaseConfig();
        /**
         * 初始化SP
         */
        PreferenceUtils.init(mContext, "TRIP");
        /**
         * 日志上报模块以及更新模块
         */
        configBugly();
        /**
         * 对于7.0以下，需要在Application创建的时候进行语言切换
         */
        //获取sp中用户设置的语言
        String strLanguage = PreferenceUtils.getString(AppConstants.LANGUAGE_TYPE, "");
        String language = PreferenceUtils.getString(AppConstants.LANGUAGE_KEY, "");
        if (getApplicationContext().getResources().getConfiguration() != null) {
            Locale locale = getApplicationContext().getResources().getConfiguration().locale;
            LogUtil.error("----------myapplication", locale.getLanguage());
            if (strLanguage.equals("follow")) {
                PreferenceUtils.applyString(AppConstants.LANGUAGE_KEY, locale.getLanguage());
                PreferenceUtils.applyString(AppConstants.LANGUAGE_TYPE, "zh");
            }

        }
        if (!language.isEmpty() && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            if (strLanguage.equals("follow")) {
//                LanguageUtil.changeAppLanguage(mContext, locale.getLanguage());
                LanguageUtil.changeAppLanguage(mContext, "zh");
            } else {
                LanguageUtil.changeAppLanguage(mContext, language);
            }
        }
        /**
         * 初始化数据库
         */
        DataBaseConfig.setDBVersion(1);
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                DataBaseConfig.initRealm(mContext);
                Looper.loop();
            }
        }.start();

        ChatClient.Options options = new ChatClient.Options();
        //必填项，appkey获取地址：kefu.easemob.com，“管理员模式 > 渠道管理 > 手机APP”页面的关联的“AppKey”
        options.setAppkey("1400200617025820#kefuchannelapp82470");
        //必填项，tenantId获取地址：kefu.easemob.com，“管理员模式 > 设置 > 企业信息”页面的“租户ID”
        options.setTenantId("82470");
        // Kefu SDK 初始化
        if (!ChatClient.getInstance().init(this, options)) {
            return;
        }
        // Kefu EaseUI的初始化
        UIProvider.getInstance().init(this);
        /**
         * 极光推送模块
         */
        JPushInterface.setDebugMode(debug);
        JPushInterface.init(this);
        //友盟
        UMConfigure.init(this, "5fb4849c257f6b73c096643a", "romeex", UMConfigure.DEVICE_TYPE_PHONE, "");
        initLocalCoin();
    }

    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.transparent, android.R.color.darker_gray);//全局设置主题颜色
                return new MaterialHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    private void initLocalCoin() {

        AppConstants.System.coins.clear();

        WalletMainBean.CoinBean coin1 = new WalletMainBean.CoinBean();
        coin1.setCoinName("REX");
        coin1.setCoinNameCobo("REX");
        coin1.setCoinNameAlias("REX");

        WalletMainBean.CoinBean coin2 = new WalletMainBean.CoinBean();
        coin2.setCoinName("XUSD");
        coin2.setCoinNameCobo("REX");
        coin1.setCoinNameAlias("XUSD");

        WalletMainBean.CoinBean coin3 = new WalletMainBean.CoinBean();
        coin3.setCoinName("USDT");
        coin3.setCoinNameCobo("ETH_USDT");
        coin1.setCoinNameAlias("USDT(ERC20)");

        WalletMainBean.CoinBean coin4 = new WalletMainBean.CoinBean();
        coin4.setCoinName("USDT");
        coin4.setCoinNameCobo("TRON_USDT");
        coin4.setCoinNameAlias("USDT(TRC20)");

        AppConstants.System.coins.add(coin1);
        AppConstants.System.coins.add(coin2);
        AppConstants.System.coins.add(coin3);
        AppConstants.System.coins.add(coin4);

    }

    private void configBugly() {

        switch (MyApplication.getEnvironment()) {
            case AppConstants.AppStatus.TEST:
                break;
            case AppConstants.AppStatus.CHECK:
                LogUtil.init(true);
                Bugly.init(getApplicationContext(), AppConstants.BUGLY_APP_ID, true);
                break;
            case AppConstants.AppStatus.RELEASE:
                LogUtil.init(false);
                //配置bug上报用户ID
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (!TextUtils.isEmpty(UserUtils.getCurrentUserAddress())) {
                            CrashReport.setUserId(UserUtils.getCurrentUserAddress());
                            LogUtil.debug("wallet_address:", UserUtils.getCurrentUserAddress());
                        }
                    }
                }, 1000);
//        Beta.tipsDialogLayoutId = R.layout.dialog_version_check;
                //延迟3.5s后检查
                Beta.initDelay = 1 * 3500;
                Beta.storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                //添加可显示弹窗的Activity
                Beta.canShowUpgradeActs.add(MainActivity.class);
                //设置是否显示消息通知
                Beta.enableNotification = true;
                //设置是否显示弹窗中的apk信息
                Beta.canShowApkInfo = true;
                //关闭热更新能力
                Beta.enableHotfix = false;
                Bugly.init(getApplicationContext(), AppConstants.BUGLY_APP_ID, false);
                break;
            default:
                break;
        }
    }


}
